package com.dao.library;

import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.bean.DBClasses.DBOptions;
import com.bean.DBClasses.DBPapers;
import com.bean.DBClasses.DBProblemFaces;
import com.bean.DBClasses.DBProblems;
import com.bean.DBClasses.DBTeacherPaper;
import com.bean.DBClasses.RandomSelect;
import com.bean.library.DbPaper;
import com.bean.library.DbSubject;
import com.bean.library.Option;
import com.bean.library.Paper;
import com.bean.library.StatisticPaper;
import com.bean.library.Subject;
import com.bean.library.UserOption;
import com.bean.library.UserPaper;
import com.dao.BaseDao;
import com.dao.PostgreSQL;

public class PaperDaoImpl extends BaseDao implements PaperDao, PostgreSQL {

	@SuppressWarnings("deprecation")
	@Override
	public Paper getPaperByPaperId(int paperId) throws Exception {
		// TODO Auto-generated method stub
		String paperSql = "select paper_name, total_score, pass_score, start_time, last_time , status"
				+ " from Papers where paper_id = ?";
		DBPapers dbPaper = esql.query(DBPapers.class, paperSql, paperId);
		Paper paper = new Paper();
		paper.setPaperName(dbPaper.getPaperName());
		paper.setPaperScore(dbPaper.getTotalScore());
		paper.setPassScore(dbPaper.getPassScore());
		if(dbPaper.getStatus().equalsIgnoreCase(DBPapers.STATUS_EXAM_PAPER)){
			paper.setKinds(Paper.KINDS_EXAM_PAPER);
		}
		else{
			paper.setKinds(Paper.KINDS_PRACTICE_PAPER);
		}
		
		java.sql.Time time = java.sql.Time.valueOf(dbPaper.getLastTime());
		Long lastTimeMs = (long) (time.getHours() * 3600 + time.getMinutes()
				* 60 + time.getSeconds()) * 1000;
		paper.setLastTimeMs(lastTimeMs);
		// 类型转换
		Timestamp timestamp = Timestamp.valueOf(dbPaper.getStartTime());
		java.util.Date startTime = new java.util.Date(timestamp.getYear(),
				timestamp.getMonth(), timestamp.getDate());
		startTime.setHours(timestamp.getHours());
		startTime.setMinutes(timestamp.getMinutes());
		startTime.setSeconds(timestamp.getSeconds());
		// startTime =new java.util.();
		System.out.println(startTime);
		paper.setStartTime(startTime);

		ArrayList<Subject> subjectlist = new ArrayList<Subject>();
		// 试卷对应的问题查询
		String problemSql = "select p.content , p.problem_id from Problems as p join Paper_Problem  as pp "
				+ "on p.problem_id =pp.problem_id  where pp.paper_id = ? ";
		List<DBProblems> problemsSet = esql.list(DBProblems.class, problemSql,
				paperId);
		String optionSql = new String();
		String problemFaceSql = new String();
		for (int i = 0; i < problemsSet.size(); i++) {
			DBProblems dbProblem = problemsSet.get(i);
			Subject subject = new Subject();
			subject.setSubjectId(dbProblem.getProblemId().intValue());
			// 查询题面的信息
			problemFaceSql = "select content from problemfaces where problem_id = ?";
			DBProblemFaces dbProblemFace = esql.query(DBProblemFaces.class,
					problemFaceSql, dbProblem.getProblemId());
			subject.setSubjectContent(dbProblem.getContent()
					+ dbProblemFace.getContent());
			// 针对每道题查询对应的选项
			ArrayList<Option> optionList = new ArrayList<Option>();
			optionSql = "select option_id,content,right_wrong from Options where problem_id = ? ";
			List<DBOptions> dbOptionsSet = esql.list(DBOptions.class,
					optionSql, dbProblem.getProblemId());
			int numberOfAnswers = 0;
			for (int j = 0; j < dbOptionsSet.size(); j++) {
				if (dbOptionsSet.get(j).getRightWrong().equalsIgnoreCase("R")) {
					numberOfAnswers++;
				}
			}
			for (int k = 0; k < dbOptionsSet.size(); k++) {
				Option option = new Option();
				option.setOptContent(dbOptionsSet.get(k).getContent());
				option.setFatherSubjectId(dbProblem.getProblemId());
				option.setOptId(dbOptionsSet.get(k).getOptionId());
				if (numberOfAnswers > 1) {
					option.setMulti(true);
					subject.setMulti(true);
				} else {
					option.setMulti(false);
					subject.setMulti(false);
				}
				optionList.add(option);
			}
			subject.setOptList(optionList);
			subjectlist.add(subject);
		}
		paper.setSubjectList(subjectlist);
		return paper;
	}

	@Override
	public Subject getSubjectBySubId(int subId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Option getOptionByOptId(int optId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isOptinRight(int optId) throws Exception {// 这倒题是不是对的？
		// TODO Auto-generated method stub
		String optionSql = "select right_wrong from Options where option_id = ?";
		DBOptions dbOption = esql.query(DBOptions.class, optionSql, optId);
		if (dbOption.getRightWrong().equalsIgnoreCase("R")) {
			return true;
		}
		return false;
	}

	@SuppressWarnings("deprecation")
	@Override
	public boolean insertPaper(DbPaper dbPaper) throws Exception {
		// TODO Auto-generated method stub
		/*
		 * 插入一张试卷
		 * 由于需要创建paper<--->problem的关系表，所以需要先插入Paper获得这个PaperId，因为paperid只有插入操作才能得到
		 * 。
		 * 
		 * 由于需要创建problem<---->Option的关系表，所以要先插入problem获得problemId，
		 * 因为problemId只有插入操作才能得到。
		 */

		/*
		 * 先插入papers表（）通过dbPaper的方法获得信息，如dbPaper.getPaperName();获得这张试卷的idpaperId
		 * = insertXXXXXXX();
		 */

		String status = "U";
		Timestamp dataBaseStartTime = new Timestamp(9999, 01, 01, 00, 0, 0, 0);
		Timestamp dataBasenoEnterTime = new Timestamp(9999, 01, 01, 00, 0, 0, 0);
		Long lastTimeMs = (long) 0;
		java.sql.Time dataBaseLastTime = new Time(0, 0, 0);
		if (dbPaper.getStatus()) {
			status = "N";
			java.util.Date startTime = dbPaper.getStartTime();
			System.out.println("entered");
			System.out.println(startTime.getYear());
			dataBaseStartTime = new Timestamp(startTime.getYear(),
					startTime.getMonth(), startTime.getDate(),
					startTime.getHours(), startTime.getMinutes(),
					startTime.getSeconds(), 0);
			System.out.println("entered1");
			dataBasenoEnterTime = new Timestamp(startTime.getYear(),
					startTime.getMonth(), startTime.getDate(),
					startTime.getHours(), startTime.getMinutes() + 30,
					startTime.getSeconds(), 0);
			lastTimeMs = dbPaper.getLastTimeMs();

			dataBaseLastTime = new java.sql.Time(
					(int) (lastTimeMs / 1000 / 3600),
					(int) (lastTimeMs / 1000 % 3600) / 60,
					(int) ((lastTimeMs / 1000 % 3600) % 60));
		}

		String paperSql = "insert into Papers(paper_name,status,total_score,pass_score,start_time,no_enter_time,subject_id,last_time) values (?,?,?,?,?,?,?,?)";
		System.out.println(esql.update(paperSql, dbPaper.getPaperName(),
				status, dbPaper.getPaperScore(), dbPaper.getPassScore(),
				dataBaseStartTime, dataBasenoEnterTime, dbPaper.getCourseId(),
				dataBaseLastTime));
		esql.commitTransaction();

		paperSql = "select max(paper_id) as paper_id from papers ";
		DBPapers dataBasePaper = esql.query(DBPapers.class, paperSql);
		int paperId = dataBasePaper.getPaperId();

		// 维护修改其他表
		String teacherPapersql = "insert into teacher_paper(teacher_id,paper_id,submit_time) values(?,?,?)";
		System.out.println(dbPaper.getTeacherId());
		Timestamp timestamp = new Timestamp(dbPaper.getDateNow().getYear(), dbPaper.getDateNow().getMonth(), dbPaper.getDateNow().getDate(), dbPaper.getDateNow().getHours(), dbPaper.getDateNow().getMinutes(), 0, 0);
		esql.update(teacherPapersql, dbPaper.getTeacherId(), paperId,timestamp);
		esql.commitTransaction();

		String problemSql = "select max(problem_id) as problem_id from Problems";
		DBProblems dataBaseProblem = esql.query(DBProblems.class, problemSql);
		int problemId = dataBaseProblem.getProblemId();
		System.out.println(problemId);
		String problemFaceSql = "select max(problemface_id) as problemface_id from Problemfaces";
		DBProblemFaces dataBaseProblemFace = esql.query(DBProblemFaces.class,
				problemFaceSql);
		int problemFaceId = dataBaseProblemFace.getProblemfaceId();
		System.out.println(problemFaceId);
		String optionSql = new String();

		ArrayList<Subject> dbSubjectList = dbPaper.getSubjectList();

		int subCount = dbSubjectList.size();
		System.out.println("size " + subCount);
		for (int i = 0; i < subCount; i++) {
			System.out.println("has entered");
			DbSubject dbSubject = (DbSubject) dbSubjectList.get(i);
			problemSql = "insert into Problems ( content, subject_id, difficulty ) values(?,?,?)";
			esql.update(problemSql, dbSubject.getSubjectContent(),
					String.valueOf(dbSubject.getCourseId()),
					String.valueOf((dbSubject.getDifficulty())));
			esql.commitTransaction();
			problemId++;
			// paper_problem table
			String paperProblemSql = "insert into paper_problem ( paper_id, problem_id ) values(?,?)";
			esql.update(paperProblemSql, paperId, problemId);
			// problemFaces table
			problemFaceSql = "insert into problemfaces ( problem_id,content ) values(?,?)";
			esql.update(problemFaceSql, problemId, dbSubject.getSurface());
			esql.commitTransaction();

			ArrayList<Option> optionList = dbSubject.getOptList();
			int optCount = optionList.size();
			for (int j = 0; j < optCount; j++) {
				UserOption userOption = (UserOption) optionList.get(j);
				String rightWrong = "W";
				if (userOption.isChecked()) {
					rightWrong = "R";
				}
				optionSql = "insert into options ( problem_id, content, right_wrong ) values(?,?,?)";
				esql.update(optionSql, problemId, userOption.getOptContent(),
						rightWrong);
				esql.commitTransaction();
			}
		}
		return true;
	}

	@Override
	public int getCountOfProblem(String subjectId, int difficulty)
			throws Exception {// 查出某一科目，某一难度的题目有多少个
		// TODO Auto-generated method stub
		String dataBaseProblemSql = "select count(problem_id) as problem_id from problems where subject_id = ? and difficulty = ?";
		DBProblems dataBaseProblem = esql.query(DBProblems.class,
				dataBaseProblemSql, subjectId, String.valueOf(difficulty));
		return dataBaseProblem.getProblemId();
	}

	/*
	 * getPaperRandomly(Integer problemCountEachDifficulty[]);
	 * 参数说明：problemCountEachDifficulty[1]为难度为1的题目数目
	 * problemCountEachDifficulty[2]为难度为2的题目数目
	 * 
	 * 、
	 */
	@Override
	public Paper getPaperRandomly(String subjectId,
			Integer[] problemCountEachDifficulty) throws Exception {
		// TODO Auto-generated method stub
		Paper paper = new Paper();
		paper.setPaperName("随机试卷");
		paper.setKinds(Paper.KINDS_PRACTICE_PAPER);
		int problemLength = problemCountEachDifficulty.length;
		ArrayList<Subject> subjectList = new ArrayList<Subject>();
		for (int i = 1; i < problemLength; i++) {
			int recordInDataBase = getCountOfProblem(subjectId, i);
			int countOfProblem = Math.min(recordInDataBase,
					problemCountEachDifficulty[i]);
			System.out.println("countOfProblem---"+countOfProblem);
			
			Integer[] randomSelectedProblem = RandomSelect.getRandomSelect(recordInDataBase,countOfProblem);
			
			for(int x = 0;x<randomSelectedProblem.length;x++){
				System.out.println("randomSelectedProblem["+x+"]="+randomSelectedProblem[x]);
			}
			
			
			//开始随即取题
			for (int j = 0; j < countOfProblem; j++) {
				Subject subject = new Subject();
				int problemId = 0;
				int rt = randomSelectedProblem[j];
				String problemSql = "select * from problems where subject_id=? and difficulty=?  offset ? limit 1";				
				DBProblems dataBaseProblem = esql.query(DBProblems.class, problemSql, subjectId,String.valueOf(i),rt);
				problemId =dataBaseProblem.getProblemId(); 
				ArrayList<Option> optionList = new ArrayList<Option>();
				String optionSql = "select option_id, content,right_wrong from options where problem_id = ?";
				List<DBOptions> dataBaseOptionList = esql.list(DBOptions.class,
						optionSql, problemId);
				int numOfOpion = dataBaseOptionList.size();
				int rightOfOptions = 0;
				for (int k = 0; k < numOfOpion; k++) {
					if(dataBaseOptionList.get(k).getRightWrong().equalsIgnoreCase("R")){
						rightOfOptions++;
					}
				}
				for (int k = 0; k < dataBaseOptionList.size(); k++) {
					Option option = new Option();
					option.setFatherSubjectId(problemId);
					option.setOptId(dataBaseOptionList.get(k).getOptionId());
					if (rightOfOptions > 1) {
						option.setMulti(true);
						subject.setMulti(true);
					} else {
						option.setMulti(false);
						subject.setMulti(false);
					}
					option.setOptContent(dataBaseOptionList.get(k).getContent());
					optionList.add(option);
				}
				subject.setSubjectId(problemId);
				subject.setSubjectContent("(难度："+i+")"+dataBaseProblem.getContent());
				subject.setOptList(optionList);
				subjectList.add(subject);
			}

		}
		paper.setSubjectList(subjectList);
		return paper;
	}

	@SuppressWarnings("deprecation")
	@Override
	public ArrayList<StatisticPaper>[] getStatisticPaper(String teacherId,
			String subjectId) throws Exception {
		// 初始化
		ArrayList[] statisticPaperList = new ArrayList[3];
		for (int i = 0; i < 3; i++) {
			statisticPaperList[i] = new ArrayList<StatisticPaper>();
		}

		/*String teacherPaperSql = "select paper_id , submit_time  from teacher_paper where teacher_id = ?";
		List<DBTeacherPaper> dataBaseTeacherPaperList = esql.list(
				DBTeacherPaper.class, teacherPaperSql, teacherId);
		int teacherPaperNo = dataBaseTeacherPaperList.size();
		for (int i = 0; i < teacherPaperNo; i++) {
			String paperSql = "select paper_name,status from papers where paper_id=? and subject_id =?";
			DBPapers dataBasePaper = esql.query(DBPapers.class, paperSql,
					dataBaseTeacherPaperList.get(i).getPaperId(), subjectId);
			if (dataBasePaper.getStatus().equalsIgnoreCase("N")) {

				Timestamp timestamp = dataBaseTeacherPaperList.get(i)
						.getSubmitTime();
				java.util.Date date = new Date(timestamp.getYear(),
						timestamp.getMonth(), timestamp.getDate(),
						timestamp.getHours(), timestamp.getMinutes());
				// StatisticPaper statisticPaper = new
				// StatisticPaper(dataBaseTeacherPaperList.get(i).getPaperId(),date,);
			}
		}*/
		

		//测试数据
		//statisticPaperList[0]放的是examPaper
		StatisticPaper statisticPaper = new StatisticPaper(1243,"考试题",new Date(2012-1900,11,9,18,23,23),53,StatisticPaper.TYPE_EXAM_PAPER);
		statisticPaperList[0].add(statisticPaper);		
		//statisticPaperList[1]放的是sparePaper
		for(int i = 0;i<5;i++){
			StatisticPaper statisticPaper1 = new StatisticPaper(1243,"备用题"+(i+1),new Date(2012-1900,11,9,18,23,23),53,StatisticPaper.TYPE_SPARE_PAPER);
			statisticPaperList[1].add(statisticPaper1);
		}		
		//statisticPaperList[2]放的是practicPaper
		for(int i = 0;i<5;i++){
			StatisticPaper statisticPaper2 = new StatisticPaper(1243,"模拟题"+(i+1),new Date(2012-1900,11,9,18,23,23),53,StatisticPaper.TYPE_PRACTICE_PAPER);
			statisticPaperList[2].add(statisticPaper2);
		}
		return statisticPaperList;
	}

	/*
	 * 
	 * 
	 * 
	 * 已经实现
	 * 
	 * 
	 * (non-Javadoc)
	 * 
	 * @see com.dao.library.PaperDao#getStandadPaperById(int)
	 */
	@Override
	public UserPaper getStandadPaperById(int paperId) {
		// TODO Auto-generated method stub
		// 获得白卷
//		Paper paper = null;
//		UserPaper userPaper = null;
//		try {
//			paper = getPaperByPaperId(paperId);
//			userPaper = new UserPaper();
//
//			ArrayList<Subject> userSubjectList = new ArrayList<Subject>();
//			ArrayList<Subject> subjectList = paper.getSubjectList();
//			int subjectCount = subjectList.size();
//			for (int i = 0; i < subjectCount; i++) {
//				Subject userSubject = new Subject();
//				Subject subject = paper.getSubject(i);
//				userSubject.setMulti(subject.isMulti());
//				userSubject.setSubjectId(subject.getSubjectId());
//				userSubject.setSubjectContent(subject.getSubjectContent());
//				ArrayList<Option> userOptionList = new ArrayList<Option>();
//				int optionCount = subject.getOptList().size();
//				for (int j = 0; j < optionCount; j++) {
//					UserOption userOption = new UserOption();
//					Option option = subject.getOptList().get(j);
//					userOption.setMulti(option.isMulti());
//					userOption.setOptContent(option.getOptContent());
//					userOption.setOptId(option.getOptId());
//					userOption.setFatherSubjectId(option.getFatherSubjectId());
//					userOptionList.add(userOption);
//					if (this.isOptinRight(option.getOptId())) {
//						userOption.setChecked(true);
//					} else {
//						userOption.setChecked(false);
//					}
//				}
//				userSubject.setOptList(userOptionList);
//				userSubjectList.add(userSubject);
//			}
//			userPaper.setSubjectList(userSubjectList);
//
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		return userPaper;
		
		UserPaper userPaper = new UserPaper();
		userPaper.setPaperName("数据库原理");
		
		ArrayList<Subject> subList = new ArrayList<Subject>();
		//userPaper.setSubList();
		for(int i = 0 ;i < 11;i++){
			ArrayList<Option> optList = new ArrayList<Option>();
			Subject subject = new Subject();
			subject.setSubjectContent("题目"+i);
			for(int j = 0;j<4;j++){
				UserOption opt = new UserOption();
				opt.setChecked(j%4==0?true:false);
				opt.setOptContent("选项"+j);
				optList.add(opt);
			}
			subList.add(subject);
			subject.setOptList(optList);
		}
		userPaper.setSubjectList(subList);
		return userPaper;
	}

}
